package com.uccart_project.controller;

import com.uccart_project.model.Aranceles;
import com.uccart_project.model.Estudiante;
import com.uccart_project.model.Inventario;
import com.uccart_project.model.Presupuesto;
import com.uccart_project.model.Planilla;
import com.uccart_project.model.CuentasPagar;
import com.uccart_project.model.ConciliacionBancaria;
import com.uccart_project.model.Usuario;
import com.uccart_project.ui.forms.UI_Alumno;
import com.uccart_project.ui.forms.UI_Login;
import com.uccart_project.util.EntityManagerFactorySingleton;
import java.awt.GraphicsEnvironment;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class Controller_Application {

    public static final String PANEL_PRINCIPAL = "PanelPrincipal";
    public static final String PANEL_INFORMACION = "PanelInformacion";
    public static final String PANEL_MODULO = "PanelModulo";

    private UI_Login uiLogin;
    private UI_Alumno uiAlumno;
    private Estudiante estudiante;
    private Usuario usuario;
    private Inventario inventario;
    private Planilla planilla;

    public Controller_Application() {
        this.uiLogin = new UI_Login(this);
    }

    /**
     *
     */
    public void iniciar() {
        this.uiLogin.setVisible(true);
    }

    public void cerrarSession() {
        EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
        em.getEntityManagerFactory().getCache().evictAll();

        this.estudiante = null;
        this.uiLogin = new UI_Login(this);
        this.uiAlumno.dispose();
        this.uiLogin.setVisible(true);

        this.uiAlumno = null;
    }

    public void crearMenuPrincipal() {
        try {
            this.uiAlumno = new UI_Alumno(this);
            GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
            this.uiAlumno.setMaximizedBounds(env.getMaximumWindowBounds());
            this.uiAlumno.setExtendedState(uiLogin.getExtendedState() | JFrame.MAXIMIZED_BOTH);

            this.uiLogin.dispose();
            this.uiAlumno.setVisible(true);
        } catch (Exception e) {
            System.out.println("crearMenuPrincipalnofunciona" + e.toString());
        }
    }

    public void mostrarPanelPrincipal() {
        this.uiAlumno.cambiarPanel(PANEL_PRINCIPAL);
    }

    public void mostrarPanelModulo() {
        this.uiAlumno.cambiarPanel(PANEL_MODULO);
    }

    public void mostrarPanelLogin() {
        this.uiAlumno.cambiarPanel(PANEL_PRINCIPAL);
    }

    public void mostrarPanelInformacion() {
        this.uiAlumno.cambiarPanel(PANEL_INFORMACION);
    }

    public void verificarUsuario(String usId, String password) {
        this.uiLogin.setEnabled(false);
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            em.flush();
            this.usuario = em.find(Usuario.class, usId);
            em.getTransaction().commit();
            em.close();
            if (usuario != null) {
                if (usuario.getUsPw().equals(password)) {
                    System.out.println("Entro como usuario");
                    crearMenuPrincipal();
                } else {
                    JOptionPane.showMessageDialog(uiLogin, "Usuario o contraseña invalidos", "ERROR", 0, new javax.swing.ImageIcon(getClass().getResource("/com/uccart_project/ui/iconos/Notificacion.png")));
                }
            } else {
                JOptionPane.showMessageDialog(uiLogin, "Usuario o contraseña invalidos", "ERROR", 0, new javax.swing.ImageIcon(getClass().getResource("/com/uccart_project/ui/iconos/Notificacion.png")));
            }
        } catch (Exception e) {
            System.out.println("verificarUsuario " + e.toString());
            JOptionPane.showMessageDialog(uiLogin, "Error al intentar conectar a la base de datos", "ERROR", 0, new javax.swing.ImageIcon(getClass().getResource("/com/uccart_project/ui/iconos/Notificacion.png")));
        }
        this.uiLogin.setEnabled(true);
    }

    public boolean updateContrasena(String nueva) {
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            usuario.setUsPw(nueva);
            em.merge(usuario);
            em.getTransaction().commit();
            em.close();
        } catch (Exception e) {
            System.out.println("updateContrasena " + e.toString());
            return false;
        }
        return true;
    }

    public boolean coinciden(String antigua) {
        return usuario.getUsPw().equals(antigua);
    }

    public String getEstudianteCelular() {

        return this.estudiante.getEstCelular().toString();
    }

    /**
     *
     * @return
     */
    public String getEstudianteTelefono() {

        return this.estudiante.getEstTelefono().toString();
    }

    /**
     *
     * @return
     */
    public String getEstudianteCorreo() {
        return this.estudiante.getEstCorreo().toString();
    }

    /**
     *
     * @return
     */
    public String getEstudianteDireccion() {
        return this.estudiante.getEstDireccion();
    }

    /**
     *
     * @return
     */
    public String getEstudianteTrabajo() {
        return this.estudiante.getEstTrabajo();
    }

    public String getEstInfo() {
        return this.estudiante.getEstId() + "  " + estudiante.getEstNombre() + " " + estudiante.getEstApellido1() + "  " + estudiante.getEstApellido2();
    }

    public String getUserInfo() {
        return this.usuario.getUsId() + "  " + usuario.getUsNombre() + " " + usuario.getUsTipo();
    }
    //////////////////////////////////////////////////////////////////////////////////////
    /*METODOS DE INVENTARIO*/
    /*METODO DE buscar INVENTARIO*/

    public ArrayList<Inventario> consultarInventario(Integer text) {
        //System.out.println("consultarInventario");
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            em.flush();
            result = em.createNamedQuery("Inventario.findByInventarioId").setParameter("inventarioId", text).getResultList();
            em.getTransaction().commit();
            em.close();

        } catch (Exception e) {
            System.out.println("Buscar inventario " + e.toString());

        }
        // System.out.println("se caeinventariobuscar");
        return new ArrayList<>(result);
    }
//    /*METODO DE LISTAR TODOS LOS INVENTARIOS*/

    public ArrayList<Inventario> listarInventario() {
        //System.out.println("listarInventario");
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            em.flush();
            result = em.createNamedQuery("Inventario.findAll").getResultList();
            em.getTransaction().commit();
            em.close();

        } catch (Exception e) {
            System.out.println("Listar Inventario " + e.toString());

        }
        // System.out.println("se caeinventariolistar");
        return new ArrayList<>(result);

    }
//
//    //MODIFICAR INVENTARIO
    public boolean modificarInventario(Inventario inventario) {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            result = em.createNamedQuery("Inventario.findByInventarioId").setParameter("inventarioId", inventario.getInventarioId()).getResultList();
            if (result != null) {
                if (result.size() != 0) {
                    Iterator InventarioIterator = result.iterator();
//                  System.out.println("Listar Inventario entra ");
                    while (InventarioIterator.hasNext()) {
                        Inventario inv = (Inventario) InventarioIterator.next();
                        if (inventario.getInventarioId().equals(inv.getInventarioId())) {
                            //System.out.println("Listar Inventario entra ");
                            inv.setInventarioNombre(inventario.getInventarioNombre());
                            inv.setInventarioId(inventario.getInventarioId());
                            inv.setInventarioMarca(inventario.getInventarioMarca());
                            inv.setInventarioModelo(inventario.getInventarioModelo());
                            inv.setInventarioValor(inventario.getInventarioValor());
                            inv.setInventarioCantidad(inventario.getInventarioCantidad());
                            inv.setInventarioProveedor(inventario.getInventarioProveedor());
                            em.persist(inv);
                            //em.merge(inv);
                            //em.remove(inv);
                            em.flush();
                        }

                        //em.persist(inventario);
                    }
                    em.getTransaction().commit();
                    em.close();
                }
            }
        } catch (Exception e) {
            System.out.println("Fallo el modificar " + e.toString());
            JOptionPane.showMessageDialog(null, "el codigo digitado no existe");
            return false;
        }
        return true;
    }

    //INSERTAR INVENTARIO
    public boolean insertaInvetario(Inventario inventario) {
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            Inventario inv = new Inventario();
            inv = inventario;
            em.persist(inv);
            em.flush();
            em.getTransaction().commit();
            em.close();
        } catch (Exception e) {
            System.out.println("insertarInventario " + e.toString());
            return false;
        }
        return true;
    }

    //ELIMINAR INVENTARIO
    public boolean eliminarInventario(Integer text) {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            result = em.createNamedQuery("Inventario.findByInventarioId").setParameter("inventarioId", text).getResultList();
            if (result.size() != 0) {
                Iterator InventarioIterator = result.iterator();
                while (InventarioIterator.hasNext()) {
                    Inventario inv = (Inventario) InventarioIterator.next();
                    if (text.equals(inv.getInventarioId())) {
                        //System.out.println("Listar Inventario entra ");
                        em.merge(inv);
                        em.remove(inv);
                        em.flush();
                    }
                }

                em.getTransaction().commit();
                em.close();
            }
        } catch (Exception e) {
            System.out.println("Fallo el eliminar " + e.toString());
            return false;
        }
        return true;
    }
    //inventario
    //////////////////////////////////////////////////////////////////////////////////////

    //PLANILLA
    public boolean insertaPlanilla(Planilla planilla) {
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            Planilla plani = new Planilla();
            plani = planilla;
            em.persist(plani);
            em.flush();
            em.getTransaction().commit();
            em.close();
        } catch (Exception e) {
            System.out.println("insertarPlanilla " + e.toString());
            return false;
        }
        return true;
    }

    public boolean modificarPlanilla(Planilla planilla) {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            result = em.createNamedQuery("Planilla.findByIdEmpleado").setParameter("IdEmpleado", planilla.getIdEmpleado()).getResultList();
            if (result != null) {
                if (result.size() != 0) {
                    Iterator PlanillaIterator = result.iterator();
                    while (PlanillaIterator.hasNext()) {
                        Planilla plani = (Planilla) PlanillaIterator.next();
                        if (planilla.getIdEmpleado().equals(plani.getIdEmpleado())) {

                            plani.setIdEmpleado(planilla.getIdEmpleado());
                            plani.setNombre(planilla.getNombre());
                            plani.setApellido(planilla.getApellido());
                            plani.setCorreo(planilla.getCorreo());
                            plani.setNumeroTel(planilla.getNumeroTel());
                            plani.setDiaContratacion(planilla.getDiaContratacion());
                            plani.setSalario(planilla.getSalario());

                            em.persist(plani);
                            //em.merge(inv);
                            //em.remove(inv);
                            em.flush();
                        }

                        //em.persist(inventario);
                    }
                    em.getTransaction().commit();
                    em.close();
                }
            }
        } catch (Exception e) {
            System.out.println("Fallo el modificar de planilla " + e.toString());
            return false;
        }
        return true;
    }

    public boolean eliminarPlanilla(Integer text) {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            result = em.createNamedQuery("Planilla.findByIdEmpleado").setParameter("IdEmpleado", text).getResultList();
            if (result.size() != 0) {
                Iterator planillaIterator = result.iterator();
                while (planillaIterator.hasNext()) {
                    Planilla plani = (Planilla) planillaIterator.next();
                    if (text.equals(plani.getIdEmpleado())) {
                        em.merge(plani);
                        em.remove(plani);
                        em.flush();
                    }
                }

                em.getTransaction().commit();
                em.close();
            }
        } catch (Exception e) {
            System.out.println("Fallo el eliminar " + e.toString());
            return false;
        }
        return true;
    }

    public ArrayList<Planilla> consultarPlanilla(Integer text) {
        System.out.println("consultarPlanilla");
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            em.flush();
            result = em.createNamedQuery("Planilla.findByIdEmpleado").setParameter("IdEmpleado", text).getResultList();
            em.getTransaction().commit();
            em.close();

        } catch (Exception e) {
            System.out.println("Buscar planilla " + e.toString());

        }
        return new ArrayList<>(result);
    }

    public ArrayList<Planilla> listarPlanilla() {
        //System.out.println("listarInventario");
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            em.flush();
            result = em.createNamedQuery("Planilla.findAll").getResultList();
            em.getTransaction().commit();
            em.close();

        } catch (Exception e) {
            System.out.println("Listar planilla " + e.toString());

        }
        // System.out.println("se caeinventariolistar");
        return new ArrayList<>(result);
    }

    ////////////////////////////////////////////////////////////////////////////////////////
    //CUENTAS POR PAGAR
    public boolean insertaCuentasPagar(CuentasPagar cuentapagar) {
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            CuentasPagar cuentPag = new CuentasPagar();
            cuentPag = cuentapagar;
            em.persist(cuentPag);
            em.flush();
            em.getTransaction().commit();
            em.close();
        } catch (Exception e) {
            System.out.println("insertarCuentaPagar " + e.toString());
            return false;
        }
        return true;
    }

    public boolean modificarCuentasPagar(CuentasPagar cuentaspagar) {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            result = em.createNamedQuery("CuentasPagar.findByNumeroCuenta").setParameter("NumeroCuenta", cuentaspagar.getNumeroCuenta()).getResultList();
            if (result != null) {
                if (result.size() != 0) {
                    Iterator CuentasPagarIterator = result.iterator();
                    while (CuentasPagarIterator.hasNext()) {
                        CuentasPagar cuenPag = (CuentasPagar) CuentasPagarIterator.next();
                        if (cuentaspagar.getNumeroCuenta().equals(cuenPag.getNumeroCuenta())) {

                            cuenPag.setFecha(cuentaspagar.getFecha());
                            cuenPag.setNumeroCuenta(cuentaspagar.getNumeroCuenta());
                            cuenPag.setMonto(cuentaspagar.getMonto());
                            cuenPag.setNombre(cuentaspagar.getNombre());
                            cuenPag.setFechaPago(cuentaspagar.getFechaPago());
                            cuenPag.setPorConcepto(cuentaspagar.getPorConcepto());

                            em.persist(cuenPag);
                            //em.merge(inv);
                            //em.remove(inv);
                            em.flush();
                        }

                        //em.persist(inventario);
                    }
                    em.getTransaction().commit();
                    em.close();
                }
            }
        } catch (Exception e) {
            System.out.println("Fallo el modificar de cuentas por pagar " + e.toString());
            return false;
        }
        return true;

    }
    
        public boolean eliminarCuentasPagar(Integer text) {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            result = em.createNamedQuery("CuentasPagar.findByNumeroCuenta").setParameter("NumeroCuenta", text).getResultList();
            if (result.size() != 0) {
                Iterator CuentasPagarIterator = result.iterator();
                while (CuentasPagarIterator.hasNext()) {
                    CuentasPagar cuenPag = (CuentasPagar) CuentasPagarIterator.next();
                    if (text.equals(cuenPag.getNumeroCuenta())){
                        em.merge(cuenPag);
                        em.remove(cuenPag);
                        em.flush();
                    }
                }

                em.getTransaction().commit();
                em.close();
            }
        } catch (Exception e) {
            System.out.println("Fallo el eliminar " + e.toString());
            return false;
        }
        return true;
    }

    public ArrayList<CuentasPagar> consultarCuentasPagar(Integer text) {
        System.out.println("CuentasPagar");
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            em.flush();
            result = em.createNamedQuery("CuentasPagar.findByNumeroCuenta").setParameter("NumeroCuenta", text).getResultList();
            em.getTransaction().commit();
            em.close();

        } catch (Exception e) {
            System.out.println("Buscar cuentas por pagar " + e.toString());

        }
        return new ArrayList<>(result);
    }
    
        public ArrayList<CuentasPagar> listarCuentasPagar() {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            em.flush();
            result = em.createNamedQuery("CuentasPagar.findAll").getResultList();
            em.getTransaction().commit();
            em.close();

        } catch (Exception e) {
            System.out.println("Listar cuentas por pagar " + e.toString());

        }
        // System.out.println("se caeinventariolistar");
        return new ArrayList<>(result);
    }
    //CUENTAS POR PAGAR
    
    ////////////////////////////////////////////////////////////////////////////////////////
    
  

    /*METODOS DE ARANCEL*/
    //INSERTAR ARANCEL
    public boolean insertarArancel(Aranceles arancel) {
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            Aranceles aran = new Aranceles();
            aran = arancel;
            em.persist(aran);
            em.flush();
            em.getTransaction().commit();
            em.close();
        } catch (Exception e) {
            System.out.println("fallo el insertar arancel" + e.toString());
            return false;
        }
        return true;
    }

    //LISTAR ARANCELES
    public ArrayList<Aranceles> listarArancel() {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            em.flush();
            result = em.createNamedQuery("Aranceles.findAll").getResultList();
            em.getTransaction().commit();
            em.close();

        } catch (Exception e) {
            System.out.println("Listar Aranceles fallo" + e.toString());

        }
        // System.out.println("se caeinventariolistar");
        return new ArrayList<>(result);
    }

    /*ELIMINAR ARANCEL*/
    public boolean eliminarArancel(Integer text) {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            result = em.createNamedQuery("Aranceles.findByArancelesId").setParameter("arancelesId", text).getResultList();
           // System.out.println("se caeinventariolistar");
            if (result.size() != 0) {
                Iterator ArancelIterator = result.iterator();
//                  System.out.println("Listar Inventario entra ");
                while (ArancelIterator.hasNext()) {
                    Aranceles aran = (Aranceles) ArancelIterator.next();
                    if (text.equals(aran.getArancelesId())) {
                        //System.out.println("Listar Inventario entra ");
                        em.merge(aran);
                        em.remove(aran);
                        em.flush();
                    }
                }

                em.getTransaction().commit();
                em.close();
            }
        } catch (Exception e) {
            System.out.println("Fallo el eliminar Arancel" + e.toString());
            return false;
        }
        return true;
    }
    
    

    /*BUSCAR ARANCEL*/
    public ArrayList<Aranceles> consultarArancel(Integer text) {
        List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            em.flush();
            result = em.createNamedQuery("Aranceles.findByArancelesId").setParameter("arancelesId", text).getResultList();
            em.getTransaction().commit();
            em.close();

        } catch (Exception e) {
            System.out.println("Buscar arancel " + e.toString());

        }
        return new ArrayList<>(result);
    }
//    



/*MODIFICAR ARANCEL*/
       public boolean modificarArancel(Aranceles ara) {
         List result = null;
        try {
            EntityManager em = EntityManagerFactorySingleton.getFactory().createEntityManager();
            em.getTransaction().begin();
            result = em.createNamedQuery("Aranceles.findByArancelesId").setParameter("arancelesId", ara.getArancelesId()).getResultList();
            if (result != null) {
                if (result.size() != 0) {
                    Iterator CuentasPagarIterator = result.iterator();
                    while (CuentasPagarIterator.hasNext()) {
                        Aranceles cuenPag = (Aranceles) CuentasPagarIterator.next();
                        if (ara.getArancelesId().equals(cuenPag.getArancelesId())) {

                            cuenPag.setArancelesId(ara.getArancelesId());
                            cuenPag.setArancelesDescripcion(ara.getArancelesDescripcion());
                            cuenPag.setArancelesPrecio(ara.getArancelesPrecio());
                            cuenPag.setArancelesTipo(ara.getArancelesTipo());
                 

                            em.persist(cuenPag);
                            //em.merge(inv);
                            //em.remove(inv);
                            em.flush();
                        }

                        //em.persist(inventario);
                    }
                    em.getTransaction().commit();
                    em.close();
                }
            }
        } catch (Exception e) {
            System.out.println("Fallo el modificar de arancel" + e.toString());
            return false;
        }
        return true;
    }

}



/////////////////////////////////////////////////////////////////////////////////////
